package com.ruoyi.system.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class PdfUtils {
    private final Path tempDir = Paths.get(System.getProperty("java.io.tmpdir"), "pdf-splitter");

    public PdfUtils() {
        try {
            Files.createDirectories(tempDir);
        } catch (IOException e) {
            throw new RuntimeException("无法创建临时目录", e);
        }
    }

    // 拆分PDF文件
    public List<String> splitPdf(MultipartFile file) throws IOException {
        String folderName = UUID.randomUUID().toString();
        Path outputDir = tempDir.resolve(folderName);
        Files.createDirectories(outputDir);

        Path tempFilePath = tempDir.resolve("uploaded_" + file.getOriginalFilename());
        Files.write(tempFilePath, file.getBytes());

        List<String> pageFiles = new ArrayList<>();

        try (PDDocument document = PDDocument.load(tempFilePath.toFile())) {
            int totalPages = document.getNumberOfPages();

            for (int i = 0; i < totalPages; i++) {
                try (PDDocument newDocument = new PDDocument()) {
                    newDocument.addPage(document.getPage(i));
                    String outputFileName = String.format("page_%03d.pdf", i + 1);
                    Path outputPath = outputDir.resolve(outputFileName);
                    newDocument.save(outputPath.toFile());
                    pageFiles.add(outputPath.toString());
                }
            }
        } finally {
            Files.deleteIfExists(tempFilePath);
        }

        return pageFiles;
    }

    // 创建ZIP文件
}
